#!/usr/bin/env python

#DEBUG
import logging
import units
import user
import webapp2

from google.appengine.api import users
from google.appengine.ext import db
from lxml import etree
from pykml.factory import KML_ElementMaker as KML

#Takes one argument:
#uid:   User's id (datastore key)
class COP(webapp2.RequestHandler):
    #This should be chopped up into functions eventually
    def get(self):
        #Get a user id from the request
        uid = self.request.get("uid")

        #Gracefully exit if not
        if not uid:
            self.error(501)
            self.response.out.write("No user specified (Error 0401)")
            return

        #See if we have a matching user in the datastore
        userobj = user.User.get(uid)
        if not userobj:
            self.error(502)
            self.response.out.write("No user object (Error 0402)")
            return

        #Main document
        kml = KML.kml()
        document = KML.Document(KML.name("cop.kml"))
        kml.append(document)
        #Folder to hold the COP
        mainFolder = KML.Folder(
            KML.name("Intel Report")
            )
        document.append(mainFolder)
        #Maps folder names to folder objects
        folderobj = {}

        #Loop through the buildings owned by the user
        for building in userobj.buildingList:
            #Make sure we have a folder object
            buildingObj = db.Model.get(building)
            if buildingObj.folder not in folderobj.keys():
                folderobj[buildingObj.folder] = KML.Folder(
                    KML.name(buildingObj.folder),
                    id = buildingObj.__class__.__name__ + "Folder"
                    )
            #Make an entry in the appropriate folder for the building
            folderobj[buildingObj.folder].append(
                KML.Placemark(
                    KML.name(buildingObj.__class__.__name__),
                    KML.Point(
                        KML.coordinates("%f,%f,%i"%(buildingObj.location.lon, buildingObj.location.lat, buildingObj.altitude))
                        ),
                    id=str(buildingObj.key())
                    )
                )

            #Make entries for any radar hits
            for hit in buildingObj.radarHits:
                hitObj = db.Model.get(hit)
                #Make sure there's a RadarHits folder
                if hitObj.folder not in folderobj.keys():
                    folderobj[hitObj.folder] = KML.Folder(
                        KML.name(hitObj.folder),
                        id = hitObj.__class__.__name__ + "Folder"
                        )
                #Make an entry in the folder for each hitObj
                folderobj[hitObj.folder].append(
                    KML.Placemark(
                        KML.name(hitObj.__class__.__name__),
                        KML.LineString(
                            KML.altitudeMode("absolute"),
                            KML.coordinates("%f,%f,%i %f,%f,%i"%(
                                hitObj.collectorLocation.lon,
                                hitObj.collectorLocation.lat,
                                hitObj.collectorAltitude,
                                hitObj.emitterLocation.lon,
                                hitObj.emitterLocation.lat,
                                hitObj.emitterAltitude)
                                )
                            ),
                        id=str(hitObj.key())
                        )
                    )

        #Put the folders in the KML
        for folder in folderobj:
            mainFolder.append(folderobj[folder])

        self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
        #self.response.headers['Content-Type'] = 'text/xml'
        self.response.out.write('<?xml version="1.0" encoding="UTF-8"?>' +
                                etree.tostring(kml, pretty_print=True))

app = webapp2.WSGIApplication([
                               ('/cop.kml', COP)
                               ], debug=True)